﻿using IdentityServer3.Core;
using IdentityServer3.Core.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
using System.Web.Helpers;

[assembly: OwinStartupAttribute(typeof(Ptolemy.MvcWeb.Startup))]
namespace Ptolemy.MvcWeb
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // todo: replace with serilog
            //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());

            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Plolemy",
                    SigningCertificate = LoadCertificate(),

                    Factory = new IdentityServerServiceFactory()
                                .UseInMemoryUsers(Users.Get())
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(Scopes.Get()),

                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true,
                    }
                });
            });

            //app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44376/identity",
                ClientId = "mvc",
                ResponseType = "id_token",
                RedirectUri = "https://localhost:44376/",

                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,

                //Notifications = new OpenIdConnectAuthenticationNotifications
                //{
                //    SecurityTokenValidated = async n =>
                //    {
                //        var nid = new ClaimsIdentity(
                //            n.AuthenticationTicket.Identity.AuthenticationType,
                //            Constants.ClaimTypes.GivenName,
                //            Constants.ClaimTypes.Role);

                //        // get userinfo data
                //        var userInfoClient = new UserInfoClient(n.Options.Authority + "/connect/userinfo");

                //        var userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
                //        userInfo.Claims.ToList().ForEach(ui =>
                //        {
                //            nid.AddClaim(new Claim(ui.Type, ui.Value));
                //        });

                //        // keep the id_token for logout
                //        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                //        // add access token for sample API
                //        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                //        // keep track of access token expiration
                //        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                //        // add some other app specific claim
                //        nid.AddClaim(new Claim("app_specific", "some data"));

                //        n.AuthenticationTicket = new AuthenticationTicket(
                //            nid,
                //            n.AuthenticationTicket.Properties);
                //    },

                //    RedirectToIdentityProvider = n =>
                //    {

                //        switch (n.ProtocolMessage.RequestType)
                //        {
                //            case OpenIdConnectRequestType.Authentication:

                //                break;
                //            case OpenIdConnectRequestType.Logout:
                //                {
                //                    var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                //                    if (idTokenHint != null)
                //                    {
                //                        n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                //                    }
                //                }
                //                break;
                //            case OpenIdConnectRequestType.Token:
                //                break;
                //            default:
                //                break;
                //        }
                //        return Task.FromResult(0);
                //    }
                //}
            });
        }

        X509Certificate2 LoadCertificate()
        {
            return new X509Certificate2(
                string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
        }
    }
}
